<!--新增/编辑/查看-->
<template>
  <el-dialog
    class="base-dialog"
    :class="{ readonly: readOnly }"
    :custom-class="'panna-dialog_medium'"
    :title="title"
    :visible.sync="dialogVisible"
    :append-to-body="true"
    :before-close="handleClose"
    @closed="closedDialog"
  >
    <p slot="title">{{ title }}</p>
    <div class="main-container">
      <el-collapse v-model="activeName">
        <el-collapse-item :title="deviceManage.deviceInformation" name="1">
          <template>
            <div>
              <el-form
                ref="formData"
                v-loading="formLoading"
                :rules="formRules"
                :model="formData"
                label-width="130px"
                class="base-pipeline-layout system-customer-form"
              >
                <el-form-item
                  :label="deviceManage.deviceNumber"
                  prop="deviceNum"
                >
                  <el-input
                    v-model="formData.deviceNum"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.deviceName"
                  prop="deviceName"
                >
                  <el-input
                    v-model="formData.deviceName"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.deviceModel"
                  prop="deviceModel"
                >
                  <el-input
                    v-model="formData.deviceModel"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.deviceFactory"
                  prop="deviceManufactor"
                >
                  <el-input
                    v-model="formData.deviceManufactor"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.installationAddress"
                  prop="installAddress"
                >
                  <el-input
                    v-model="formData.installAddress"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.calibrationCycle"
                  prop="calibrationCycle"
                >
                  <el-input
                    v-model="formData.calibrationCycle"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.releaseDate"
                  prop="throwInDate"
                >
                  <el-date-picker
                    v-model="formData.throwInDate"
                    :disabled="readOnly"
                    type="date"
                    :placeholder="deviceManage.selectDate"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item
                  :label="deviceManage.acceptState"
                  prop="acceptStatusCode"
                >
                  <el-select
                    v-model="formData.acceptStatusCode"
                    value-key="formData.acceptStatusCode"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  >
                    <el-option
                      v-for="(item, index) in acceptStatusCodeList"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :label="deviceManage.technicalParameter"
                  prop="technologyParameter"
                >
                  <el-input
                    v-model="formData.technologyParameter"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.functionalPerformance"
                  prop="performing"
                >
                  <el-input
                    v-model="formData.performing"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.condition"
                  prop="runCondition"
                >
                  <el-input
                    v-model="formData.runCondition"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  />
                </el-form-item>
                <el-form-item
                  :label="deviceManage.recognitionStatus"
                  prop="approveStatusCode"
                >
                  <el-select
                    v-model="formData.approveStatusCode"
                    value-key="formData.approveStatusCode"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  >
                    <el-option
                      v-for="(item, index) in approveStatusCodeList"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item :label="deviceManage.useTo" prop="purposeCode">
                  <el-select
                    v-model="formData.purposeCode"
                    value-key="formData.purposeCode"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  >
                    <el-option
                      v-for="(item, index) in purposeCodeList"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :label="deviceManage.instrumentStatus"
                  prop="instrumentStatusCode"
                >
                  <el-select
                    v-model="formData.instrumentStatusCode"
                    value-key="formData.instrumentStatusCode"
                    :disabled="readOnly"
                    :placeholder="deviceManage.enter"
                  >
                    <el-option
                      v-for="(item, index) in instrumentStatusCodeList"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </el-collapse-item>
        <el-collapse-item :title="deviceManage.sampleTestingDetails" name="2">
          <template>
            <el-button
              type="primary"
              icon="el-icon-plus"
              :disabled="readOnly"
              size="mini"
              @click="addSampleDetection"
              >{{ operateType.add }}</el-button
            >
            <el-table
              ref="table"
              :data="formData.sampleDetections"
              :border="true"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                prop="sampleCategoryName"
                :label="deviceManage.sampleCategory"
              />
              <el-table-column prop="num" :label="deviceManage.testNumber" />
              <el-table-column
                prop="detectionItemName"
                :label="deviceManage.testingItems"
              />
              <el-table-column
                prop="standardMethod"
                :label="deviceManage.detectionMethod"
              />
              <el-table-column :label="operateType.action" width="140">
                <template slot-scope="{ row }">
                  <div class="base-table-operation">
                    <el-link
                      type="danger"
                      @click="deleteSampleDetection(row)"
                      >{{ operateType.delete }}</el-link
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-collapse-item>
        <el-collapse-item :title="deviceManage.picture" name="3">
          <template>
            <el-form
              ref="formData"
              v-loading="formLoading"
              :rules="formRules"
              :model="formData"
              label-width="130px"
              class="base-pipeline-layout system-customer-form"
            >
              <el-form-item
                :label="deviceManage.instrumentImage"
                prop="picturePath"
              >
                <BaseMultipleUpload
                  v-model="formData.picturePath"
                  :disabled="readOnly"
                  :accept="acceptImg"
                  :tip="deviceManage.imagesFormatUploaded"
                  list-type="picture-card"
                  :business-type="businessType"
                  @removeImg="removeImg"
                />
              </el-form-item>
            </el-form>
          </template>
        </el-collapse-item>
        <el-collapse-item :title="deviceManage.annex" name="4">
          <template>
            <div class="chioseFileDiv">
              <el-button
                slot="trigger"
                size="small"
                icon="el-icon-paperclip"
                type="primary"
                @click="choiseFile()"
                >{{ deviceManage.clickUpload }}</el-button
              >{{ deviceManage.fileUploadCannotExceed10 }}
              <el-upload
                ref="upload"
                class="base-upload"
                name="FilePath"
                :multiple="true"
                action
                :headers="headers"
                :show-file-list="false"
                :show-upload-list="false"
                :limit="10"
                :accept="accept"
                :disabled="readOnly"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :on-change="upload"
                :auto-upload="false"
                :file-list="fileList"
              ></el-upload>
            </div>
            <div>
              <el-table
                ref="table"
                :data="formData.filePath"
                style="width: 100%"
              >
                <el-table-column
                  prop="originalFileName"
                  :label="deviceManage.fileName"
                >
                  <template slot-scope="scope">
                    <span>
                      {{ scope.$index + 1 + scope.row.originalFileName }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column :label="operateType.action" width="140">
                  <template slot-scope="{ row }">
                    <div class="base-table-operation">
                      <el-link type="danger" @click="deletefile(row)">{{
                        operateType.delete
                      }}</el-link>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <BasePagination
                :total="pagination.total"
                :page-index="pagination.pageIndex"
                :page-size="pagination.pageSize"
                @sizeChange="sizeChange"
                @currentChange="currentChange"
              />
            </div>
          </template>
        </el-collapse-item>
      </el-collapse>
    </div>
    <span v-if="!readOnly" slot="footer" class="base-dialog-footer">
      <el-button :disabled="!submitLoad" type="primary" @click="submitForm">{{
        operateType.save
      }}</el-button>
      <el-button @click="handleClose">{{ operateType.cancel }}</el-button>
    </span>
    <ChoiceDetectionItemDialog
      v-model="dialogDetectionItem"
      @DetectionItemClose="DetectionItemClose"
    />
  </el-dialog>
</template>

<script>
import _ from "lodash";
import {
  create,
  update,
  getDeviceInfo,
  deleteFileRecord,
} from "../../../api/DeviceManage/SysBusinessDevice.js";
import { getDictList } from "../../../api/System/SystemDict";
import { formdataify } from "../../../utils/index";
import { getToken } from "../../../utils/auth";
export default {
  name: "SysBusinessDeviceInfoEdit",
  components: {},
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      // 页面标题
      title: "",
      headers: { Authorization: getToken() },
      activeName: ["1", "2", "3", "4"],
      // 文件上传
      dialogFile: "true",
      multiple: true,
      uploadLoad: false,
      // 上传文件类型
      fileImgType: 1,
      // 上传文件类型
      businessType: "40",
      // 接受状态
      acceptStatusCodeList: [],
      // 认可状态
      approveStatusCodeList: [],
      // 仪器状态
      instrumentStatusCodeList: [],
      // 文件集合
      fileList: [],
      deleteTables: [],
      // 检测项目弹窗
      dialogDetectionItem: false,
      fileSize: 11200,
      acceptImg: ".jpg,.jpeg,.png",
      accept: ".pdf,.doc,.xls,.docx,.xlsx,.zip",
      dialogImageUrl: "",
      dialogVisible: false,
      // 用途
      purposeCodeList: [],
      // 提交加载状态
      submitLoad: true,
      // 表单
      formData: {
        picturePath: [],
        filePath: [],
        // 检测样品数据
        sampleDetections: [],
      },
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      // 表单验证
      formRules: {
        deviceNum: [
          {
            required: true,
            message: this.$t("DeviceManage.enterDeviceNumber"),
          },
        ],
        deviceName: [
          { required: true, message: this.$t("DeviceManage.enterDeviceName") },
        ],
      },
      // 表单加载状态
      formLoading: false,
    };
  },
  computed: {
    operateType() {
      return this.$t("ModuleSysBusiness.OperateType") || {};
    },
    deviceManage() {
      return this.$t("DeviceManage") || {};
    },
    hint() {
      return this.$t("ModuleSysBusiness.Hint") || {};
    },
  },
  // 监听父页面状态
  watch: {
    value: function() {
      this.dialogVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  methods: {
    // 初始化
    async init() {
      this.formLoading = true;
      getDictList({ dictCode: "AcceptStatusCode" }).then((res) => {
        this.acceptStatusCodeList = res.data;
      });
      getDictList({ dictCode: "ApproveStatusCode" }).then((res) => {
        this.approveStatusCodeList = res.data;
      });
      getDictList({ dictCode: "PurposeCode" }).then((res) => {
        this.purposeCodeList = res.data;
      });
      getDictList({ dictCode: "InstrumentStatusCode" }).then((res) => {
        this.instrumentStatusCodeList = res.data;
      });
      this.title = this.readOnly
        ? this.$t("DeviceManage.viewDevice")
        : this.editId
          ? this.$t("DeviceManage.editDevice")
          : this.$t("DeviceManage.addDevice");
      if (this.editId) {
        getDeviceInfo({ id: this.editId })
          .then((res) => {
            this.formData = res.data;
            this.formData.acceptStatusCode = res.data.acceptStatusCode + "";
            this.formData.approveStatusCode = res.data.approveStatusCode + "";
            this.formData.purposeCode = res.data.purposeCode + "";
            this.formData.instrumentStatusCode =
              res.data.instrumentStatusCode + "";
            this.pagination.total = res.data.filePath.length;
          })
          .finally(() => {
            this.formLoading = false;
          });
      } else {
        this.formData.sampleDetections = [];
        this.formLoading = false;
      }
    },
    // 提交表单
    submitForm: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        // 校验表单必填项
        this.$refs.formData.validate((valid) => {
          if (valid) {
            // 当前编辑ID是否存在 存在则去更新
            const requestData = JSON.parse(JSON.stringify(this.formData));
            if (this.editId) {
              this.editAPI(requestData);
            } else {
              // 新增
              this.addAPI(requestData);
            }
          } else {
            this.submitLoad = true;
            this.$message.error(this.$t("ModuleSysBusiness.Hint.provideCompleteInformation"));
          }
        });
      }
    }, 2000),
    // 关闭选择检测项目触发事件
    DetectionItemClose(data, fileId) {
      for (let i = 0; i < data.length; i++) {
        // 将检测项目标拼接字符串
        for (let o = 0; o < data[i].detectionItemData.length; o++) {
          const detectionItem = {
            detectionItemId: data[i].detectionItemData[o].id,
            sampleCategoryName: data[i].detectionItemData[o].sampleCategoryName,
            num: data[i].detectionItemData[o].num,
            detectionItemName: data[i].detectionItemData[o].detectionItemName,
            standardMethod: data[i].detectionItemData[o].standardMethod,
          };
          this.formData.sampleDetections.push(detectionItem);
        }
      }
    },
    // 复选框
    handleSelectionChange(val) {
      this.deleteTables = val;
    },
    // 新增样品检测
    addSampleDetection() {
      this.dialogDetectionItem = true;
    },
    // 复制样品检测
    copySampleDetection() {
      for (let i = 0; i < this.deleteTables.length; i++) {
        this.deleteTables[i].index =
          this.formData.sampleDetections[
            this.formData.sampleDetections.length - 1
          ].index + 1;
        var data = JSON.parse(JSON.stringify(this.deleteTables[i]));
        this.formData.sampleDetections.push(data);
      }
    },
    // 删除样品检测
    deleteSampleDetection(rows) {
      var index = this.formData.sampleDetections.findIndex(
        (arr) => arr.id === rows.id
      );
      this.formData.sampleDetections.splice(index, 1);
    },
    // 上传文件
    choiseFile() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    handleRemove(file, fileList) {
      this.$emit("deleteFile", `${this.$base}${file.response.data}`);
    },
    // 上传完成
    upload(file, fileList) {
      this.fileCount = fileList.length;
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        var data = {
          storageFileName: res.data.newFileName,
          filePath: res.data.filePath,
          originalFileName: res.data.fileName,
        };
        this.formData.filePath.push(data);
      });
    },
    removeImg(values) {
      for (let i = 0; i < this.formData.picturePath.length; i++) {
        if (this.formData.picturePath[i].storageFileName === values.name) {
          this.formData.picturePath.splice(i, 1);
        }
      }
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      const fileTypes = this.accept.split(",");
      var testmsg = file.name.substring(file.name.lastIndexOf("."));
      const checkFormat = fileTypes.includes(testmsg);
      if (!checkFormat) {
        this.uploadLoad = false;
        this.$message.error(this.$t("DeviceManage.selectFormat", this.accept));
      }
      const checkSize = file.size / 1024 < this.fileSize;
      if (!checkSize) {
        this.uploadLoad = false;
        this.$message.error(
          this.$t("DeviceManage.fileSizeLimit", this.fileSize)
        );
      }
      return checkFormat && checkSize;
    },
    // 新增接口
    addAPI(data) {
      create(data)
        .then((res) => {
          this.submitLoad = true;
          this.init();
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = true;
        });
    },
    // 编辑接口
    editAPI(data) {
      update({
        ...data,
        id: this.editId,
      })
        .then((res) => {
          this.submitLoad = true;
          this.init();
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = true;
        });
    },
    // 删除
    deletefile(rowData) {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        deleteFileRecord({ id: rowData.id })
          .then((res) => {
            getDeviceInfo({ id: this.editId })
              .then((res) => {
                this.formData.filePath = res.data.filePath;
                this.pagination.total = res.data.filePath.length;
              })
              .finally(() => {
                this.formLoading = false;
              });
          })
          .catch(() => {});
      });
    },
    // 操作成功回调用
    SuccessfulOperation() {
      this.submitLoad = true;
      this.handleClose();
    },
    // 切换页码
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getEntrustFileList();
    },
    currentChange(val) {
      this.pagination.pageIndex = val;
      this.getEntrustFileList();
    },
    // 关闭弹框
    handleClose() {
      this.$emit("input", false);
    },
    // 关闭弹框动画结束
    closedDialog() {
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
    },
  },
};
</script>

<style  scoped>
/deep/ .el-collapse-item__header {
  height: 38px;
  line-height: 20px;
  padding: 4px;
  background-color: #f1f8ff;
}
/deep/ .el-collapse-item__content {
  padding-top: 25px;
  padding-bottom: 12.5px;
}
</style>
